package com.zmn.oms.admin.controller.question;

import com.google.common.collect.Maps;
import com.zmn.brs.common.enums.EventEnum;
import com.zmn.brs.common.enums.RecordFieldEnum;
import com.zmn.brs.starter.annotation.RecordField;
import com.zmn.brs.starter.annotation.StaffOperateRecord;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.dto2.data.LayuiTableDO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.office.excel.ExportExcel;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.mcc.common.dto.staff.StaffDRO;
import com.zmn.mcc.dubbo.interfaces.staff.StaffListRemoteService;
import com.zmn.oms.admin.controller.work.list.WorkListTabBaseController;
import com.zmn.oms.business.interfaces.remark.OrderRemarkBService;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.constant.ReplyVisitQuestionConsts;
import com.zmn.oms.common.dto.ResultDTO;
import com.zmn.oms.model.entity.conf.reply.ReplyCategory;
import com.zmn.oms.model.entity.question.ReplyVisitQuestionQuery;
import com.zmn.oms.model.entity.work.OrderWorkQuery;
import com.zmn.oms.model.vo.question.ReplyVisitQuestionVO;
import com.zmn.oms.model.vo.remark.OrderRemarkDetail2VO;
import com.zmn.oms.model.vo.work.ZsOrderWorkVO;
import com.zmn.oms.services.interfaces.conf.reply.ReplyCategoryService;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkQueryBService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author ：SongWeidong
 * @date ：2020/4/20 11:12
 * @description：回访问卷管理
 */
@Slf4j
@Controller
@RequestMapping("/question/replyvisit")
public class WorkReplyVisitQuestionController extends WorkListTabBaseController {

    @Autowired
    ZsOrderWorkQueryBService zsOrderWorkQueryBService;
    @Autowired
    OrderRemarkBService orderRemarkBService;
    @Resource
    ReplyCategoryService replyCategoryService;

    @Reference(version = com.zmn.mcc.dubbo.dto.DubboConsts.INTERFACE_VERSION, check = false)
    protected StaffListRemoteService staffListRemoteService;


    @RequestMapping("list")
    public ModelAndView list(ModelAndView mv,HttpServletRequest request) {

        Integer plat = Integer.parseInt(request.getParameter("plat"));

        mv.setViewName("question/replyvisit/list");

        // 状态
        mv.addObject("plat",plat);
        // 状态
        mv.addObject("visitItems",super.getVisitCategList());
        // 状态
        mv.addObject("yesOrNo", OrderConsts.getYesOrNoObj());

        // 下单日期，默认30天
        mv.addObject("startTime", DateUtil.toString(DateUtil.addDays(DateUtil.getNow(), -30), "yyyy-MM-dd"));
        mv.addObject("endTime", DateUtil.toString(DateUtil.getNow(), "yyyy-MM-dd"));
        super.setDayLimit(mv);

        return mv;
    }

    @StaffOperateRecord(staffId = "{{#query.staffId}}",
            event = EventEnum.WORK_ORDER_QUERY,
            mapping = {
            @RecordField(field = RecordFieldEnum.STAFF_IP, value = "{{#query.ip}}"),
            @RecordField(field = RecordFieldEnum.PLAT, value = "{{#query.platWork}}")
    })
    @PostMapping("/ajax/list")
    @ResponseBody
    public ResultDTO ajaxList(@RequestBody ReplyVisitQuestionQuery query) {

        LayuiTableDO<ReplyVisitQuestionVO> data = new LayuiTableDO<>();
        data.setData(this.queryList(query));
        data.setCount(query.getTotalCount());
        return ResultDTO.success(data);
    }


    @StaffOperateRecord(staffId = "{{#query.staffId}}",
            event = EventEnum.WORK_ORDER_EXPORT,
            mapping = {
            @RecordField(field = RecordFieldEnum.STAFF_IP, value = "{{#query.ip}}"),
            @RecordField(field = RecordFieldEnum.PLAT, value = "{{#query.platWork}}")
    })
    @GetMapping(value = "/export")
    public void exportExcel(ReplyVisitQuestionQuery query, HttpServletResponse response) throws Exception {

        // 导出最多1w
        query.setPageSize(10000);
        List<ReplyVisitQuestionVO> replyVisitQuestionVOS = this.queryList(query);

        LinkedHashMap<String, String> fieldMap = Maps.newLinkedHashMap();
        fieldMap.put("orderId", "工单号");
        fieldMap.put("replyVisiterName", "回访人");
        fieldMap.put("replyItemName", "回访项目");
        fieldMap.put("receiveTime", "下单日期");
        fieldMap.put("replyVisitTime", "回访时间");
        fieldMap.put("companyName", "子公司");
        fieldMap.put("manageCompanyName", "服务公司");
        fieldMap.put("showCategTwoName", "维修品类");
        fieldMap.put("masterName", "工程师");
        fieldMap.put("statusName", "订单状态");
        fieldMap.put("replyContent", "备注");

        fieldMap.put("question1", "电话是否接听");
        fieldMap.put("question2", "工程师是否准时");
        fieldMap.put("question3", "工程师是否穿工作服");
        fieldMap.put("question4", "工程师是否穿鞋套");
        fieldMap.put("question5", "工程师是否戴口罩");
        fieldMap.put("question6", "对整体服务是否满意");
        fieldMap.put("question7", "失败原因");
        fieldMap.put("question8", "不满意/意见类型（如用户满意则不勾选此项））");
        fieldMap.put("question9", "工程师是否填写并提供表单");
        fieldMap.put("question10", "是否清楚维修原因及维修方案");
        fieldMap.put("question11", "收费金额是否与系统一致");
        fieldMap.put("question12", "工程师是否按约定上门");
        fieldMap.put("question13", "对工程师服务态度是否满意");
        fieldMap.put("question14", "是否接受一口价");
        fieldMap.put("question15", "是否按一口价标准收费");
        fieldMap.put("question16", "是否消毒");
        fieldMap.put("question17", "是否安装/维修好");
        fieldMap.put("question18", "费用是否异常（虚假核实）");

        for (ReplyVisitQuestionVO replyVisitQuestionVO : replyVisitQuestionVOS) {

            List<OrderRemarkDetail2VO> remarkDetailList = replyVisitQuestionVO.getRemarkDetailList();
            if(CollectionUtils.isEmpty(remarkDetailList)){
                continue;
            }
            remarkDetailList.forEach(e->{
                Integer mapId = e.getMapId();
                String mapValue = e.getMapValue();
                switch (mapId){
                    case ReplyVisitQuestionConsts.Question1:
                        replyVisitQuestionVO.setQuestion1(mapValue);
                        break;
                    case ReplyVisitQuestionConsts.Question2:
                        replyVisitQuestionVO.setQuestion2(mapValue);
                        break;
                    case ReplyVisitQuestionConsts.Question3:
                        replyVisitQuestionVO.setQuestion3(mapValue);
                        break;
                    case ReplyVisitQuestionConsts.Question4:
                        replyVisitQuestionVO.setQuestion4(mapValue);
                        break;
                    case ReplyVisitQuestionConsts.Question5:
                        replyVisitQuestionVO.setQuestion5(mapValue);
                        break;
                    case ReplyVisitQuestionConsts.Question6:
                        replyVisitQuestionVO.setQuestion6(mapValue);
                        break;
                    case ReplyVisitQuestionConsts.Question7:
                        replyVisitQuestionVO.setQuestion7(mapValue);
                        break;
                    case ReplyVisitQuestionConsts.Question8:
                        replyVisitQuestionVO.setQuestion8(mapValue);
                        break;
                    case ReplyVisitQuestionConsts.Question9:
                        replyVisitQuestionVO.setQuestion9(mapValue);
                        break;
                    case ReplyVisitQuestionConsts.Question10:
                        replyVisitQuestionVO.setQuestion10(mapValue);
                        break;
                    case ReplyVisitQuestionConsts.Question11:
                        replyVisitQuestionVO.setQuestion11(mapValue);
                        break;
                    case ReplyVisitQuestionConsts.Question12:
                        replyVisitQuestionVO.setQuestion12(mapValue);
                        break;
                    case ReplyVisitQuestionConsts.Question13:
                        replyVisitQuestionVO.setQuestion13(mapValue);
                        break;
                    case ReplyVisitQuestionConsts.Question14:
                        replyVisitQuestionVO.setQuestion14(mapValue);
                        break;
                    case ReplyVisitQuestionConsts.Question15:
                        replyVisitQuestionVO.setQuestion15(mapValue);
                        break;
                    case ReplyVisitQuestionConsts.Question16:
                        replyVisitQuestionVO.setQuestion16(mapValue);
                        break;
                    case ReplyVisitQuestionConsts.Question17:
                        replyVisitQuestionVO.setQuestion17(mapValue);
                        break;
                    case ReplyVisitQuestionConsts.Question18:
                        replyVisitQuestionVO.setQuestion18(mapValue);
                        break;
                }
            });
        }

        ExportExcel<ReplyVisitQuestionVO> excel = new ExportExcel<>(replyVisitQuestionVOS, fieldMap, true);
        excel.exportExcel(response, "回访问卷");
    }


    private List<ReplyVisitQuestionVO> queryList(ReplyVisitQuestionQuery query){

        OrderWorkQuery orderWorkQuery = BeanMapper.map(query,OrderWorkQuery.class);
        orderWorkQuery.setReplyVisited(GlobalConsts.YES);
        if(Objects.nonNull(query.getReplyVisitId())){
            orderWorkQuery.setReplyVisiterIdList(Collections.singletonList(query.getReplyVisitId()));
        }
        List<ZsOrderWorkVO> zsOrderWorkVOS = zsOrderWorkQueryBService.listPageOrderWorkByQueryNoRecord(orderWorkQuery);
        query.setTotalCount(orderWorkQuery.getTotalCount());
        List<ReplyVisitQuestionVO> replyVisitQuestionVOS = BeanMapper.mapList(zsOrderWorkVOS, ReplyVisitQuestionVO.class);

        Map<Integer, ReplyCategory> map = Maps.newHashMap();
        replyVisitQuestionVOS.forEach(e->{
            // 组装数据(回访人、回访项目)
            Long replyVisiterId = e.getReplyVisiterId();
            // 查询回访人名称
            ResponseDTO<StaffDRO> staffDRO = staffListRemoteService.getStaff(Integer.parseInt(replyVisiterId.toString()));
            if(staffDRO.isSuccess() && Objects.nonNull(staffDRO.getData())){
                e.setReplyVisiterName(staffDRO.getData().getRealName());
            }
            // 查询回访项目名称
            if(CollectionUtils.isNotEmpty(e.getRemarkDetailList())){
                List<OrderRemarkDetail2VO> remarkDetails = e.getRemarkDetailList().stream().filter(item ->
                        Objects.equals(item.getType(), OrderConsts.ORDER_REMARK_TYPE_REPLY)).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(remarkDetails) && remarkDetails.get(0).getCategory() > 0) {
                    Integer category = remarkDetails.get(0).getCategory();

                    ReplyCategory replyCategory = map.get(category);
                    if(replyCategory == null){
                        replyCategory = replyCategoryService.findById(category);
                        map.put(category, replyCategory);
                    }

                    if (Objects.nonNull(replyCategory)) {
                        e.setReplyItemName(replyCategory.getName());
                        e.setVisitReplyStatus(replyCategory.getStatus());
                    }
                }
            }
        });
        return replyVisitQuestionVOS;
    }

}
